package com.tjs.lucky.application.worker;

import cn.hutool.core.util.NumberUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.lucky.tjs.annotation.ElasticJobConfig;
import com.tjs.lucky.common.ActivityState;
import com.tjs.lucky.domain.activity.model.vo.ActivityVO;
import com.tjs.lucky.domain.activity.repository.IActivityRepository;
import com.tjs.lucky.domain.activity.service.stateflow.StateHandler;
import com.tjs.lucky.domain.strategy.repository.IStrategyRepository;
import com.tjs.lucky.infrastructure.utils.EmailUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Set;

/**
 * @author tianjiashu（mac）
 * @ClassName SynStockJob.java
 * @Description  同步库存  TODO: 事务控制?
 * @createTime 2023年06月20日 21:26:00
 */
@Component
@Slf4j
@ElasticJobConfig(jobName = "SynStockJob", cron = "0 0 * * * ?", shardingTotalCount = 1)
public class SynStockJob implements SimpleJob {

    @Resource
    private IActivityRepository activityRepository;

    @Resource
    private IStrategyRepository strategyRepository;


    @Resource
    private StateHandler stateHandler;


    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Resource
    private EmailUtil emailUtil;

    @SneakyThrows
    @Override
    public void execute(ShardingContext shardingContext) {
        Set<Object> activeActivitys = stringRedisTemplate.opsForHash().keys("activeActivitys");
        for (Object activityId : activeActivitys) {
            try {
                String endDateStr = (String) stringRedisTemplate.opsForHash().get("activeActivitys", activityId);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date endDate = dateFormat.parse(endDateStr);
                /*
                    同步库存
                 */
                String activityTotalCount = stringRedisTemplate.opsForValue().get("activityTotalCount:" + activityId);
                if(NumberUtil.isNumber(activityTotalCount) && Integer.parseInt(activityTotalCount)!=-1){
                    //活动参与次数不是无限的 && 更新活动库存
                    activityRepository.synActivityStockJob(activityTotalCount);
                }
                Set<Object> awardIds = stringRedisTemplate.opsForHash().keys("awardInfoList:" + activityId);
                ActivityVO activityVO = activityRepository.queryActivityInfo(Long.valueOf((String) activityId));
                for (Object awardId : awardIds) {
                    //同步奖品库存
                    String awardStock = (String) stringRedisTemplate.opsForHash().get("awardInfoList:" + activityId, awardId);
                    strategyRepository.synAwardStock(activityVO.getStrategyId(),(String) awardId,awardStock);
                }
                // 活动已经到期 关闭活动，将活动从awardInfoList删除。
                if(endDate.before(new Date())){
                    stateHandler.close(Long.valueOf((String) activityId), ActivityState.DOING);
                    stringRedisTemplate.delete(Arrays.asList("awardInfoList:" + activityId,"activityTotalCount:" + activityId));
                }
            } catch (ParseException e) {
                emailUtil.sendhtml("928301810@qq.com", "同步库存失败",(String) activityId);
                log.info("同步库存失败:"+activityId);
            }
        }
        log.info("同步库存完毕！");
    }


}
